<!--读私信-->
<script setup>
import {useStore} from "vuex";
import {useRoute, useRouter} from "vue-router";
import {onMounted, ref, watch} from "vue";
import Pagination from "@/components/common/Pagination.vue";
import ReplyAuthor from "@/components/read/ReplyAuthor.vue";
import ContentRender from "@/components/content/ContentRender.vue";
import {ElementUtils} from "@/assets/js/ElementUtils";
import {formatDate} from "@ginstone/common-utils/dist/src/utils/DateUtils";
import {setupMapState} from "@/assets/js/vuexUtils";
import {routeNames} from "@/router";
import {ArrowLeftBold} from "@element-plus/icons-vue";
import UserLink from "@/components/common/link/UserLink.vue";
import PostTextArea from "@/components/post/PostTextArea.vue";
import {ElMessageBox} from "element-plus";

const route = useRoute()
const router = useRouter()
const store = useStore();
const {currentUid} = setupMapState("Account", ['currentUid']);


//总数
const count = ref();
//总页数
const maxPage = ref();
//分页数据
const pageData = ref();
// 用户上下文
const userContext = ref()
// 回复数据
const data = ref();
// 参与用户
const users = ref();

// 回复私信 - 标题
const title = ref();
const content = ref();


// 向私信会话中添加更多的参与者
const pmAdd = () => {
  ElMessageBox.prompt("请填写用户ID，多个用逗号隔开", "邀请新用户", {
    inputValidator: (value) => {
      if (/^(\d+[，,]*)+$/.exec(value)) {
        return true;
      }
      return '格式不合法'
    }
  }).then(({value}) => {
    const loading = ElementUtils.loading({target: "#pm_read",});
    const messageId = route.params.id;
    value = value.replace(/，/g, ',')
    const userIds = value.split(',').map(i => Number(i)).filter(i => i > 0)
    store.dispatch("Message/pmAdd", {messageId, userIds}).then(res => {
      ElementUtils.notice({message: res});
    }).catch(ElementUtils.exceptionHandler).finally(() => {
      loading.close()
    })
  }).catch(r => console.log(r))
}
//回复私信
const pmReply = () => {
  const messageId = route.params.id;
  const loading = ElementUtils.loading({target: "#pm_read",});
  return store.dispatch("Message/pmReply", {
    messageId,
    title: title.value,
    content: content.value,
  }).then(res => {
    pmRead(route, true)
    title.value = undefined
    content.value = undefined
    ElementUtils.notice({message: res})
  }).catch(ElementUtils.exceptionHandler).finally(() => {
    loading.close()
  });
}
//退出到私信列表
const goOut = () => {
  router.push({name: routeNames.message.list})
}
// 踢人
const pmKick = (userId, isSelf) => {
  const messageId = route.params.id;
  return store.dispatch("Message/pmKick", {messageId, userId}).then(res => {
    ElementUtils.notice({message: res})
    if (isSelf) {
      //退出到私信列表
      goOut();
    } else {
      // 刷新
      pmRead(route, true)
    }
  }).catch(ElementUtils.exceptionHandler)
}
//读私信
const pmRead = (route, force) => {
  const messageId = route.params.id;
  const page = route.query.page;
  const loading = ElementUtils.loading({target: "#pm_read",});
  return store.dispatch("Message/pmRead", {messageId, page, force}).then(res => {
    const {hasNext, page, length: size} = res

    // 保存数据
    data.value = res.data;
    users.value = res.users
    // 获取用户信息
    for (let key in res.data) {
      const e = res.data[key]
      e.userInfo = res.userInfo.getUserInfo(e.userId)
    }

    // console.log(res)

    if (hasNext) {
      // 还有下一页
      if (count.value) {
        // count有值，说明已经看到过最后一页，使用
        pageData.value = {
          page, size, total: count.value, totalPage: maxPage.value
        }
      } else {
        // 还没看过最后一页，猜测下一页是最大页
        pageData.value = {
          page, size, total: (page + 1) * size, totalPage: page + 1
        }
      }
    } else {
      //没有下一页了，当前页就是最大页
      count.value = (page - 1) * size + res.data.length;
      maxPage.value = page;

      pageData.value = {
        page, size, total: count.value, totalPage: maxPage.value
      }
    }

  }).catch(ElementUtils.exceptionHandler).finally(() => {
    loading.close()
  });
}
// 点击踢人按钮
const onClose = (user) => {
  //操作目标是否为自己
  const isSelf = user.userId === currentUid.value
  const content = isSelf ? '即将退出会话,该操作不可逆' : `确认移除用户 ${user.username}(${user.userId})`
  const title = isSelf ? '退出会话' : "移除用户"
  ElementUtils.confirm(content, title).then(() => {
    pmKick(user.userId, isSelf)
  }).catch(r => {
    console.warn(r)
  })
}

onMounted(() => {
  pmRead(route)
})

watch(route, (nv) => {
  pmRead(nv)
})
</script>

<template>
  <div id="pm_read">
    <div class="reply-lines-border">
      <!--顶部按钮    -->
      <div class="space-between">
        <div>
          <el-button :icon="ArrowLeftBold" size="small" style="margin-right: 30px" type="primary" @click="goOut">返回</el-button>
          <pagination :data="pageData"/>
        </div>

        <div>
          <el-button-group size="small">
            <el-button type="success" @click="pmRead($route,true)">刷新</el-button>
            <el-button type="danger" @click="onClose({userId:currentUid})">退出</el-button>
          </el-button-group>
        </div>
      </div>
      <!--    参与用户-->
      <div v-if="users && users.length>0" style="text-align: left;margin-bottom: 10px">
        <h4>参与用户 -
          <el-button size="small" type="success" @click="pmAdd">添加</el-button>
        </h4>
        <el-tag v-for="(user) in users" closable @close="onClose(user)">
          <user-link :user-id="user.userId">{{ user.username }}</user-link>
        </el-tag>
      </div>
      <!--    回复内容-->
      <div>
        <el-row v-for="reply in data" class="reply-line-border">
          <!--        作者信息-->
          <el-col v-if="reply.userId!==0" :span="6" class="author-border">
            <reply-author :data="reply.userInfo"/>
          </el-col>
          <el-col :span="reply.userId!==0?18:24">
            <!--          标题和时间-->
            <div class="space-between">
              <el-tag class="reply-info-tag">{{ formatDate(reply.timestamp) }}</el-tag>
            </div>
            <div class="content-nodes">
              <h4 v-if="reply.title">{{ reply.title }}</h4>
              <content-render :data="reply.contentNodes"/>
            </div>
          </el-col>
        </el-row>
      </div>
    </div>
    <!--  回复框-->
    <div id="pm_reply_form">
      <el-input v-model="title" placeholder="标题"/>
      <!--正文文本框-->
      <div style="text-align: left">
        <post-text-area ref="editor" v-model="content"/>
      </div>
      <el-button size="small" type="success" @click="pmReply">提交</el-button>
    </div>
  </div>

</template>

<style scoped>
#pm_read {
  min-height: 100px;
}

#pm_reply_form {
  margin-top: 20px;
  border-style: dashed dashed dashed dashed;
  border-width: 1px;
}
</style>